<template>
  <div class="main-panel">
    <div class="main-header">
      <div class="header-search" @keyup.enter="loadData">
        <el-form ref="searchForm" :model="form" label-width="70px" :inline="true" label-position="left">
          <el-form-item label="姓名">
            <el-input v-model="form.name" placeholder="请输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              type="daterange"
              v-model="dates"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期" @change='dateChange'>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadData"><i class="glyphicon glyphicon-search"></i>查询</el-button>
            <el-button @click="resetForm"><i class="glyphicon glyphicon-remove-circle"></i>清空</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="header-btn">
        <el-button type="primary" icon="el-icon-plus" @click="openDiaolog(null)">添加</el-button>
      </div>
    </div>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :data="userData"
          @sort-change="sortTable"
          row-key="id"
          :border="true"
          :sort="{prop:'createTime',order:'descending'}"
          style="width: 100%">
          <el-table-column
            type="index"
            fixed
            width="50">
          </el-table-column>
          <el-table-column prop="loginName"
                           label="登录名"
                           width="140"
                           sortable="custom"/>
          <el-table-column prop="name"
                           label="姓名"
                           width="140"
                           sortable="custom"/>
          <el-table-column prop="organizationName"
                           label="所属部门"
                           :filters="organizationFilters"
                           :filter-method="filterOrganization"
                           width="100"/>
          <el-table-column prop="createTime"
                           label="创建时间"
                           width="180" sortable="custom"/>
          <el-table-column prop="sex" width="80" label="性别" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.sex | filterSex}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="age"
                           label="年龄"
                           width="100" sortable="custom" align="cneter"/>
          <el-table-column prop="phone"
                           label="电话"
                           width="120" sortable="custom"/>
          <el-table-column prop="rolesList"
                           label="角色"
                           width="120" sortable="custom"/>
          <el-table-column prop="userType"
                           label="用户类型"
                           width="120" sortable="custom">
            <template slot-scope="scope">
              <span>{{scope.row.userType | userType}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status"
                           label="状态"
                           width="80" align="center" sortable="custom">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status===0 ? '' : 'warning'">{{scope.row.status | userStatus}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="action" label="操作" align="center" width="200">
            <template slot-scope="scope">
              <div v-if="$store.getters.name !== scope.row.name">
                <el-button size="mini" @click="openDiaolog(scope.row)" :disabled="scope.row.id === 1">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteUser(scope.row.id)" :disabled="scope.row.id === 1">删除</el-button>
              </div>
              <div v-else>
                当前用户
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page.sync="form.page"
          :page-size="form.rows"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      :title="editForm.id?'修改用户':'添加用户'"
      :visible.sync="diaologVisible"
      width="600px"
      :close-on-click-modal="false"
    @close="handleClose">
      <el-alert v-if="editForm.id"
                title="密码不修改请留空"
                style="margin-bottom: 20px;"
                type="warning"/>
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="70px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录名" prop="loginName">
              <el-input v-model="editForm.loginName" placeholder="请输入登录名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="editForm.password" type="password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model="editForm.age" type="number"></el-input>
            </el-form-item>
            <el-form-item label="部门" prop="organizationId">
              <el-cascader
                v-model="editForm.organizationId"
                :options="organizations"
                :props="{checkStrictly: true, value: 'id', label: 'text' }"
                filterable
                clearable>
                <template slot-scope="{ node, data }">
                  <span><i :class="data.iconCls"></i>{{ node.label }}</span>
                </template>
              </el-cascader>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="editForm.sex">
                <el-radio-button label="0">男</el-radio-button>
                <el-radio-button label="1">女</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户类型" prop="userType">
              <el-radio-group v-model="editForm.userType">
                <el-radio-button label="0">管理员</el-radio-button>
                <el-radio-button label="1">用户</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="editForm.roleIds" multiple collapse-tags placeholder="请选择" value="">
                <el-option
                  v-for="item in roleTreeData"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-radio-group v-model="editForm.status">
                <el-radio-button label="0">正常</el-radio-button>
                <el-radio-button label="1">禁用</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaologVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { tree } from '../../api/organization'
import { dataGrid, addUser, getUesrById, editUser, deleteUser } from '../../api/user'
import { roleTree } from '../../api/role'

export default {
  name: 'userManager',
  data () {
    var validatePass = (rule, value, callback) => {
      if (!this.editForm.id && value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      pickerOpt: {
        onPick: this.convertDate
      },
      dates: [],
      form: {
        page: 1,
        rows: 10,
        sort: 't.create_time',
        order: 'desc',
        organizationId: undefined
      },
      organizations: [],
      organizationFilters: [],
      listLoading: false,
      userData: [],
      total: 0,
      diaologVisible: false,
      editForm: {
        sex: 0,
        userType: 0,
        status: 0
      },
      editFormRules: {
        loginName: [{ required: true, message: '请输入登录名称', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      roleTreeData: []
    }
  },
  created () {
    this.loadData()
  },
  methods: {
    loadData () {
      if (!this.organizations || this.organizations.length === 0) {
        tree().then(res => {
          this.organizations = res
          this.buildOrganizationFilter(res)
        })
      }
      dataGrid(this.form).then(res => {
        this.userData = res.rows
        this.total = res.total
      })
    },
    buildOrganizationFilter (organizations) {
      organizations.forEach(orga => {
        this.organizationFilters.push({ text: orga.text, value: orga.id })
        if (orga.children) {
          this.buildOrganizationFilter(orga.children)
        }
      })
    },
    filterOrganization (value, row, column) {
      return row.organizationId === value
    },
    dateChange () {
      if (!this.dates) {
        this.form.createdateStart = undefined
        this.form.createdateEnd = undefined
        return
      }
      this.form.createdateStart = this.dates[0]
      this.form.createdateEnd = this.dates[1]
    },
    changeOrg (orgData, node) {
      this.form.organizationId = orgData.id
      this.loadData()
    },
    sortTable (sortData) {
      this.form.sort = sortData.prop
      this.form.order = sortData.order === 'descending' ? 'desc' : 'asc'
      this.loadData()
    },
    resetForm () {
      this.form = {
        page: 1,
        rows: 10,
        sort: 't.create_time',
        order: 'desc'
      }
      this.dates = []
      this.loadData()
    },
    openDiaolog (row) {
      this.editForm.id = undefined
      if (row) {
        getUesrById({ id: row.id }).then(res => {
          if (res.roleIds) {
            res.roleIds = res.roleIds.split(',')
            let roleIdNumbers = []
            for (let i = 0; i < res.roleIds.length; i++) {
              roleIdNumbers[i] = Number(res.roleIds[i])
            }
            res.roleIds = roleIdNumbers
            res.rolesList = null
          }
          this.editForm = res
        })
      }
      if (!this.roleTreeData || this.roleTreeData.length === 0) {
        roleTree().then(res => {
          this.roleTreeData = res
        })
      }
      this.diaologVisible = true
    },
    submitEditForm () {
      let self = this
      self.$refs.editForm.validate(valid => {
        if (valid) {
          if (self.editForm.id) {
            editUser(self.editForm).then(res => {
              self.$message({ message: '修改成功', type: 'success' })
              self.diaologVisible = false
              self.loadData()
            })
          } else {
            addUser(self.editForm).then(res => {
              self.$message({ message: '添加成功', type: 'success' })
              self.diaologVisible = false
              self.loadData()
            })
          }
        }
      })
    },
    handleClose () {
      this.$refs.editForm.resetFields()
    },
    deleteUser (userId) {
      let self = this
      deleteUser(userId).then(() => {
        self.$message({ message: '删除成功', type: 'success' })
        self.loadData()
      })
    }
  }
}
</script>

<style scoped>

</style>
